<?php
session_start();
require 'php-captcha.inc.php';
require 'phpass/PasswordHash.php';
require 'config.php';
require 'anti_csrf.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (PhpCaptcha::Validate($_POST['signin_captcha'])) {
        if (!isset($_POST['CSRFName'])) {       
            trigger_error("No CSRFName found, probable invalid request.",E_USER_ERROR);
        }
        $name =$_POST['CSRFName'];
        $token=$_POST['CSRFToken'];
        if (!csrfguard_validate_token($name, $token)) {
            trigger_error("Invalid CSRF token.",E_USER_ERROR);
        }
 
        $con = pg_connect($dbconstr);
        if ($con == FALSE) {
            die('Unable to connect to database.');
        }

        // get data from POST data
        $username = $_POST['username'];
        $password = $_POST['password'];

        // check username syntax
        $uname_regex = '/^\w{1,'.USERNAME_MAX_CHARS.'}$/';
        if (preg_match($uname_regex, $username) !== 1) {
            die("Username format incorrect.\nRequires 1-'.USERNAME_MAX_CHARS.' alphanumeric or underscore (_) characters.");
        }

        // check password length
        if (strlen($password) < 8 || strlen($password) > 70) {
            die("Password length incorrect.\nRequires 8-70 characters.");
        }

        $hasher = new PasswordHash($hash_cost_log2, $hash_portable);

        $result = pg_prepare($con, 'signin_query', 'SELECT pwhash FROM account WHERE username = $1');
        if ($result == FALSE) {
            die('Unable to prepare statement.');
        }
        $result = pg_execute($con, 'signin_query', array($username));
        if ($result == FALSE) {
            die('Unable to execute query.');
        }

        if (pg_num_rows($result) > 0) {
            $row = pg_fetch_row($result, 0);
            $hash = $row[0];
	    pg_close($con);
            $hasher = new PasswordHash($hash_cost_log2, $hash_portable);
            if ($hasher->CheckPassword($password, $hash)) {
                $_SESSION['username'] = $username;
		include('iplocation.php');
                header('Location: /php/account.php?id='.$username);
            } else {
                echo 'Username or password incorrect.';
            }
        } else {
            echo 'Username or password incorrect.';
        }
        unset($hasher);
        
    } else {
        echo 'Invalid code entered';
    }
}
?>
